package com.spring;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LuqimeiApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String,Object> singletonObjects=new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap=new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList=new ArrayList<>();



    public LuqimeiApplicationContext(Class configClass){
        this.configClass=configClass;
        //解析配置类
        //扫描
        scan(configClass);

        //创建单例bean
        for(Map.Entry<String,BeanDefinition> entry:beanDefinitionMap.entrySet()){
            String beanName=entry.getKey();
            BeanDefinition beanDefinition=entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean=createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }

    public Object createBean(String beanName,BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getClazz();
        try {
            Constructor constructor = clazz.getDeclaredConstructor();
            Object instance = constructor.newInstance();

            //为属性赋值，进行依赖注入 TODO 此处感觉有BUG,bean创建顺序回导致可能出现空bean
            for (Field declaredField : clazz.getDeclaredFields()) {
                if(declaredField.isAnnotationPresent(Autowired.class)){

                    Object bean=getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
            }

            //Aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance=beanPostProcessor.postProcessBeforeInitialization(instance,beanName);
            }

            //初始化
            if(instance instanceof InitializingBean){
                try {
                    ((InitializingBean) instance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance=beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }

            return instance;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class configClass) {

        ComponentScan annotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path=annotation.value();
        System.out.println(path);

        //扫描类文件，使用类加载器进行加载
        ClassLoader classLoader=LuqimeiApplicationContext.class.getClassLoader();
        path=path.replace(".","/");
        URL resource = classLoader.getResource(path);
        File file=new File(resource.getFile());
        if(file.isDirectory()){
            File[] files=file.listFiles();
            for (File f:files){
                String fileName=f.getAbsolutePath();
                if(fileName.endsWith(".class")){
                    String className=fileName.substring(fileName.indexOf("com"),fileName.indexOf(".class"));
                    className=className.replace("\\",".");
                    System.out.println(className);
                    try {
                        Class<?> clazz=classLoader.loadClass(className);
                        if(clazz.isAnnotationPresent(Component.class)){
                            //..
                            // 解析类，判断当前bean类型


                            if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                //判断当前类clazz是否实现了BeanPostProcessor接口
                                //实现了直接实例化，调用对应方法
                                try {
                                    BeanPostProcessor instance= (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                    beanPostProcessorList.add(instance);
                                } catch (InstantiationException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                }
                            }


                            Component component=clazz.getDeclaredAnnotation(Component.class);
                            String beanName=component.value();

                            BeanDefinition beanDefinition=new BeanDefinition();
                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else{
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinition.setClazz(clazz);
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    }catch (ClassNotFoundException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName){
        if(beanDefinitionMap.containsKey(beanName)){
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object o=singletonObjects.get(beanName);
                return o;
            }else{
                Object bean = createBean(beanName,beanDefinition);
                return bean;
            }
        }else{
            //不存在对应bean
            throw new NullPointerException();
        }
    }
}
